package thread.java20230106;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 任务
 */
class MyTask implements Comparable<MyTask>{
    // 使用Runnable 来描述任务
    private Runnable runnable;
    //描述任务的执行时间, 采用时间戳
    private long time;

    /**
     *
     * @param runnable
     * @param after  当前时间后多久开始执行, 单位是ms
     */
    public MyTask(Runnable runnable, long after){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + after;
    }

    public void run(){
        this.runnable.run();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    /**
     * 比较两个任务的大小
     * 按照执行时间去比较
     * time越小, 任务越小(任务执行的越早, 需要放在队首)
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.getTime());
    }
}

/**
 * 定时器
 */
public class MyTimer {
    //创建一个队列, 来存储任务
    BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    Object locker = new Object();

    /**
     * 向定时器提交任务
     * @param task
     */
    public void schedule(MyTask task){
        try{
            queue.put(task);
            synchronized (locker){
                locker.notify();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public MyTimer(){

        Thread thread = new Thread(()->{
            try {
                //取出队首的任务, 判断是否需要执行
                while (true){
                    MyTask task = queue.take();
                    //如果时间未到, 把任务重新放回队列里
                    //如果时间到了, 就执行
                    if (task.getTime()>System.currentTimeMillis()){
                        queue.put(task);
                        //接下来等待一定的时间
                        synchronized (locker){
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }
                    }else {
                        task.run();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        thread.start();
    }
}
